"""
用 Python 实现一个二分查找的函数
"""
def binarysearch(arr,key):
    first = 0 # 最小值下标
    last = len(arr ) -1 # 最大值下标
    index = -1 # 记录目标下标
    while(first <= last) and (index == -1):
        """
        循环退出条件：找到目标元素或者列表已经找完
        """
        mid = (first + last) // 2 # 计算序列的中间元素下标
        if arr[mid] == key: # 若相等，则找到目标元素

            index = mid # 记录目标元素下标
        else:
            if key < arr[mid]:
                last = mid -1
            else:
                first = mid +1
    return index
arr = [1,3,5,6,8,10,1000,1304034]
print(binarysearch(arr,10))
